const factorToItems = {
	F1: [1, 4, 12, 27, 40, 42, 48, 49, 52, 53, 56, 58], // 躯体化
	F2: [3, 9, 10, 28, 38, 45, 46, 51, 55, 65], // 强迫
	F3: [6, 21, 34, 36, 37, 41, 61, 69, 73], // 人际关系
	F4: [5, 14, 15, 20, 22, 26, 29, 30, 31, 32, 54, 71, 79], // 抑郁
	F5: [2, 17, 23, 33, 39, 57, 72, 78, 80, 86], // 焦虑
	F6: [11, 24, 63, 67, 74, 81], // 敌对性
	F7: [13, 25, 47, 50, 70, 75, 82], // 恐怖
	F8: [8, 18, 43, 68, 76, 83], // 偏执
	F9: [7, 16, 35, 62, 77, 84, 85, 87, 88, 90], // 精神病性
	F10: [19, 44, 59, 60, 66, 89], // 其他（不属于上述 9 个因子的题目）
};

// 定义因子名称
const factorNames = {
	F1: "躯体化",
	F2: "强迫",
	F3: "人际关系",
	F4: "抑郁",
	F5: "焦虑",
	F6: "敌对性",
	F7: "恐怖",
	F8: "偏执",
	F9: "精神病性",
	F10: "其他",
};

export function sclAnalyzeResults(userAnswers) {
	// 初始化因子得分
	const factors = Object.keys(factorToItems).map((factor) => ({
		factor,
		name: factorNames[factor],
		score: 0,
		count: 0,
	}));

	// 遍历用户答案，计算每个因子的总分
	userAnswers.forEach((answer) => {
		const questionId = answer.questionId; // 题目 ID
		const score = parseInt(answer.answer); // 用户得分
		// 查找题目所属的因子
		for (const factor of factors) {
			if (factorToItems[factor.factor].includes(Number(questionId))) {
				factor.score += score;
				factor.count++;
				break;
			}
		}
	});

	// 计算每个因子的平均分
	factors.forEach((factor) => {
		factor.averageScore = factor.count > 0 ? factor.score / factor.count : 0;
	});

	// 计算总均分
	const totalScore = factors.reduce((sum, factor) => sum + factor.score, 0);
	const totalCount = factors.reduce((sum, factor) => sum + factor.count, 0);
	const totalAverageScore = totalCount > 0 ? totalScore / totalCount : 0;

	// 判断风险等级
	let riskLevel = "低风险";
	if (
		totalAverageScore > 1.5 ||
		factors.some((factor) => factor.averageScore > 2)
	) {
		riskLevel = "中风险";
	}
	if (
		totalAverageScore > 2.5 ||
		factors.some((factor) => factor.averageScore > 3)
	) {
		riskLevel = "高风险";
	}

	// 返回分析结果
	return {
		factors: factors.map((factor) => ({
			name: factor.name,
			averageScore: factor.averageScore.toFixed(2), // 保留两位小数
			description:
				factor.averageScore > 3
					? "严重"
					: factor.averageScore > 2
					? "中等"
					: "正常",
		})),
		totalAverageScore: totalAverageScore.toFixed(2),
		riskLevel,
		summary: {
			totalScoreDescription:
				totalAverageScore < 0.5
					? "无心理问题"
					: totalAverageScore < 1.5
					? "有点症状，发生不频繁"
					: totalAverageScore < 2.5
					? "轻到中度"
					: totalAverageScore < 3.5
					? "中到严重"
					: "十分严重",
		},
	};
}